<?php
include('/home/wwwroot/football.laulei.com/protected/extensions/Snoopy.class.php');
include('/home/wwwroot/football.laulei.com/protected/extensions/simple_html_dom_utf8.php');
error_reporting(0);
//获取澳客网北京单场信息，如果比赛已经结束，则更新比分和赔率
class GetGameInfosOkoooCommand extends CConsoleCommand  
{
    public function run($args) {
    	/*
    	$issueArry=array();
        $html = file_get_html('http://www.okooo.com/danchang/');
		$select = $html->find('select[id=SelectLotteryNo]', 0);
	    $option = $select->find('option');
	    if(isset($option)){
	    	foreach ($option as $key => $value) {
	    		array_push($issueArry, $value->value);
	    	}
	    }
		$html->clear();
		unset($html);
		*/
		//使用snoopy得到html
		$snoopy = new Snoopy;

		/*
    	$snoopy->cookies["FirstOKURL"] = "http%3A//www.okooo.com/";
    	$snoopy->cookies["First_Source"] = "www.okooo.com";
    	$snoopy->cookies["Hm_lpvt_5ffc07c2ca2eda4cc1c4d8e50804c94b"] = "1390716387";
    	$snoopy->cookies["Hm_lvt_5ffc07c2ca2eda4cc1c4d8e50804c94b"] = "1390716384";
    	$snoopy->cookies["LStatus"] = "N";
    	$snoopy->cookies["LastUrl"] = "";
    	$snoopy->cookies["LoginStr"] = "%7B%22welcome%22%3A%22%u60A8%u597D%uFF0C%u6B22%u8FCE%u60A8%22%2C%22login%22%3A%22%u767B%u5F55%22%2C%22register%22%3A%22%u6CE8%u518C%22%2C%22TrustLoginArr%22%3A%7B%22alipay%22%3A%7B%22LoginCn%22%3A%22%u652F%u4ED8%u5B9D%22%7D%2C%22tenpay%22%3A%7B%22LoginCn%22%3A%22%u8D22%u4ED8%u901A%22%7D%2C%22qq%22%3A%7B%22LoginCn%22%3A%22QQ%u767B%u5F55%22%7D%2C%22weibo%22%3A%7B%22LoginCn%22%3A%22%u65B0%u6D6A%u5FAE%u535A%22%7D%2C%22renren%22%3A%7B%22LoginCn%22%3A%22%u4EBA%u4EBA%u7F51%22%7D%2C%22baidu%22%3A%7B%22LoginCn%22%3A%22%u767E%u5EA6%22%7D%2C%22tianya%22%3A%7B%22LoginCn%22%3A%22%u5929%u6DAF%22%7D%2C%22snda%22%3A%7B%22LoginCn%22%3A%22%u76DB%u5927%u767B%u5F55%22%7D%7D%2C%22userlevel%22%3A%22%22%2C%22flog%22%3A%22hidden%22%2C%22UserInfo%22%3A%22%22%2C%22loginSession%22%3A%22___GlobalSession%22%7D";
    	$snoopy->cookies["PHPSESSID"] = "1603a3ba09ef2e33afe675545b3db0b37234d15c";
    	$snoopy->cookies["__utma"] = "56961525.2143170722.1390716384.1390716384.1390716384.1";
    	$snoopy->cookies["__utmb"] = "56961525.6.8.1390716386849";
    	$snoopy->cookies["__utmc"] = "56961525";
    	$snoopy->cookies["__utmz"] = "56961525.1390716384.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)";
    	$snoopy->cookies["pm"] = "";
		*/
		$sql = "select distinct issue from tbl_gameinfo
				where issue>=(
				select issue from tbl_gameinfoOkooo
				order by gametime desc
				limit 0,1
				)
				order by issue";
   		$issueArry=Yii::app()->db->createCommand($sql)->queryAll();
		foreach ($issueArry as $key => $value) {
			$i=0;
			$sql="select * from tbl_proxy where writetime>date(DATE_ADD(now(),INTERVAL -1 MONTH))";
	    	$ipList=Yii::app()->db->createCommand($sql)->queryAll();
			while($i<100){
				$_index = rand(0,count($ipList)-1);
				$snoopy->proxy_host = $ipList[$_index]['ipaddress'];
	    		$snoopy->proxy_port = $ipList[$_index]['port'];
	    		$snoopy->proxy_host = $ipList[$_index]['ipaddress'];
	            $snoopy->proxy_port = $ipList[$_index]['port'];
	            $snoopy->agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36";
	            $snoopy->referer = "http://www.okooo.com/jingcai/";
	            $snoopy->cookies["FirstOKURL"]="http%3A//www.okooo.com/";
	            $snoopy->cookies["First_Source"]="www.okooo.com";
	    		printf("[ipaddress=%s] [port=%s]\n", $ipList[$_index]['ipaddress'], $ipList[$_index]['port']);
				$url=sprintf("http://www.okooo.com/danchang/%s/", $value["issue"]);
				printf("%s\n", $url);
				try{
					if($snoopy->fetch($url)) { 
			      		break;
					}
				}
				catch(Exception $e){
					$proxyObj=Proxy::model()->find(
				    			array(
				    				'condition'=>'ipaddress=:ipaddress and port=:port',
				    				'params'=>array(
				    							':ipaddress'=>$ipList[$_index]['ipaddress'],
				    							':port'=>$ipList[$_index]['port'],
				    							)
				    				)
				    			);
					$proxyObj->status=1;
					$proxyObj->update();
					printf("update status to 1![ip={%s}] [port=%s]\n", $ipList[$_index]['ipaddress'], $ipList[$_index]['port']);
					$sql="select * from tbl_proxy where status=0";
	    			$ipList=Yii::app()->db->createCommand($sql)->queryAll();
				}
				$i++;
			}
			if($i>=100){
	            printf("无服务器可用！\n");
	            return;
	        }
			
			$htmlIssue = str_get_html($snoopy->results);
			if(!isset($htmlIssue)){
	    		continue;
	    	}
			$issue=$value;//期号
			foreach($htmlIssue->find('tr[class=alltrObj]') as $gamesTr) {
				$gameIndex=trim($gamesTr->find("span[class='xh']", 0)->plaintext);

				$gameTime=$gamesTr->find("td[class=switchtime]", 0);
				if(isset($gameTime->title)){
					$gameTime=$gameTime->title;
					$gameTime=mb_substr($gameTime, 4, 19, "utf-8");
				}

				$gameType=trim($gamesTr->find("td[class=td1] a", 0)->plaintext);
				$gameType=$gameType=iconv('GB2312', 'UTF-8//TRANSLIT//IGNORE', $gameType);

				$hometeam=trim($gamesTr->find("span[class=homenameobj]", 0)->plaintext);
				$hometeam=iconv('GB2312', 'UTF-8//TRANSLIT//IGNORE', $hometeam);
				$awayteam=trim($gamesTr->find("span[class=awaynameobj]", 0)->plaintext);
				$awayteam=iconv('GB2312', 'UTF-8//TRANSLIT//IGNORE', $awayteam);
				
				$result=trim($gamesTr->find("td[class=td6]", 0)->plaintext);
				$result=explode('-', $result);
				$homegoal=$result[0];
				$awaygoal=$result[1];
				$result=array_filter($result);
				if(empty($result)){
					$homegoal=-1;
					$awaygoal=-1;
				}

				$gameid = $result=trim($gamesTr->find("td[class=td8] a", 0)->href);
				$gameid=str_replace("/soccer/match/","",$gameid);
				$gameid=str_replace("/odds/","",$gameid);
				$gameid=str_replace("javascript:warnMsg('","",$gameid);
				$gameid=str_replace("');","",$gameid);
				printf("[gameIndex=%s] [gameTime=%s] [gameType=%s] [hometeam=%s] [awayteam=%s] [homegoal=%s] [awaygoal=%s] [gameid=%s]\n", $gameIndex, $gameTime, $gameType, $hometeam, $awayteam, $homegoal, $awaygoal, $gameid);

				$bfurl=sprintf("http://www.okooo.com/soccer/match/%s/exchanges/", $gameid);//必发数据地址
				printf("必发数据地址：%s\n", $bfurl);

				try{
					if(!$snoopy->fetch($bfurl)) { 
						printf("try 失败 %s\n", $bfurl);
			      		continue;
					}
				}
				catch(Exception $e){
					if(!$snoopy->fetch($bfurl)) { 
						printf("catch 到 try 失败 %s\n", $bfurl);
			      		continue;
					}
				}

				$htmlBf = str_get_html($snoopy->results);
				if(!isset($htmlBf) || !is_object($htmlBf)){
					printf("htmlBf 为空\n");
		    		continue;
		    	}

		    	$table = $htmlBf->find("div[class=bfTable] table", 0);
		    	if(!isset($table)){
		    		$htmlBf->clear();
					unset($htmlBf);
		    		continue;
		    	}
		    	$tr=$table->find("tr", 2);
		    	$bfprice3=$tr->find("td", 5)->plaintext;//胜挂牌价
		    	$bfexchange3=$tr->find("td", 6)->plaintext;//胜成交量

		    	$tr=$table->find("tr", 3);
		    	$bfprice1=$tr->find("td", 5)->plaintext;//平挂牌价
		    	$bfexchange1=$tr->find("td", 6)->plaintext;//负挂牌价
		    	
		    	$tr=$table->find("tr", 4);
		    	$bfprice0=$tr->find("td", 5)->plaintext;//平成交量
		    	$bfexchange0=$tr->find("td", 6)->plaintext;//负成交量
		    	$htmlBf->clear();
				unset($htmlBf);

				printf("[bfprice3=%s] [bfexchange3=%s] [bfprice1=%s] [bfexchange1=%s] [bfprice0=%s] [bfexchange0=%s]\n", $bfprice3, $bfexchange3, $bfprice1, $bfexchange1, $bfprice0, $bfexchange0);


				$gameInfoOkoooObj=GameInfoOkooo::model()->find(array('condition'=>'gameid=:gameid','params'=>array(':gameid'=>$gameid)));
                if (!isset($gameInfoOkoooObj)){
                    printf(date("Y-m-d H:i:s") . " end find gameid [%s], it's not set\n", $gameid);
                    $gameInfoOkoooObj=new GameInfoOkooo;
                    $gameInfoOkoooObj->gameid=$gameid;
                    $gameInfoOkoooObj->issue=$value["issue"];
                    $gameInfoOkoooObj->gameindex=$gameIndex;
                    $gameInfoOkoooObj->gametype=$gameType;
                    $gameInfoOkoooObj->hometeam=$hometeam;
                    $gameInfoOkoooObj->awayteam=$awayteam;
                    $gameInfoOkoooObj->homegoal=$homegoal;
                    $gameInfoOkoooObj->awaygoal=$awaygoal;
                    $gameInfoOkoooObj->gametime=$gameTime;
                    $gameInfoOkoooObj->bfprice3=$bfprice3;
                    $gameInfoOkoooObj->bfprice1=$bfprice1;
                    $gameInfoOkoooObj->bfprice0=$bfprice0;
                    $gameInfoOkoooObj->bfexchange3=$bfexchange3;
                    $gameInfoOkoooObj->bfexchange1=$bfexchange1;
                    $gameInfoOkoooObj->bfexchange0=$bfexchange0;
                    $gameInfoOkoooObj->writetime=date("Y-m-d H:i:s");
                    $gameInfoOkoooObj->updatetime=date("Y-m-d H:i:s");
                    $gameInfoOkoooObj->save();
                    //printf(date("Y-m-d H:i:s") . " [期号：%s] [序号：%s] [时间：%s] [类型：%s] [主队：%s] [让球：%s] [客队：%s] [主进：%s] [客进：%s] [胜：%s] [平：%s] [负：%s]\n", $value, $gameIndex, $gameTime, $gameType, $homeTeam, $rateBall, $awayTeam, $homeGoal, $awayGoal, $euroOdds3, $euroOdds1, $euroOdds0);
                }
                else{
                    $gameInfoOkoooObj->bfprice3=$bfprice3;
                    $gameInfoOkoooObj->bfprice1=$bfprice1;
                    $gameInfoOkoooObj->bfprice0=$bfprice0;
                    $gameInfoOkoooObj->bfexchange3=$bfexchange3;
                    $gameInfoOkoooObj->bfexchange1=$bfexchange1;
                    $gameInfoOkoooObj->bfexchange0=$bfexchange0;
                    $gameInfoOkoooObj->updatetime=date("Y-m-d H:i:s");
                    if ($gameInfoOkoooObj->update()) {
                        printf("update [期号：%s] [序号：%s] [bfprice3=%s] [bfexchange3=%s] [bfprice1=%s] [bfexchange1=%s] [bfprice0=%s] [bfexchange0=%s]\n", $value["issue"], $gameIndex, $bfprice3, $bfexchange3, $bfprice1, $bfexchange1, $bfprice0, $bfexchange0);
                    }
                }
			}
			
			$htmlIssue->clear();
			unset($htmlIssue);
		}
    }
}